<script lang="ts" setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import conf from "@/conf/conf";
import { ElInput, ElNotification, ElMessageBox, ElMessage } from "element-plus";
import type { InputInstance } from "element-plus";
import { CircleClose, Edit } from "@element-plus/icons-vue";
const InputRef = ref<InputInstance>();
// 定义两个响应式变量 input 和 show
interface input {
  qualificationName: string;
  materialName: string[];
  inputValue: string;
  id: number;
}
const input = ref<input[]>([]);

// 显示操作成功的提示信息
const successMessage = () => {
  ElNotification({
    title: "操作成功",
    message: "操作材料成功",
    type: "success",
  });
};
// 显示错误消息的函数
const ErrorMessage = () => {
  ElNotification({
    title: "错误",
    message: "出现错误，请检查输入数据",
    type: "error",
  });
};

// 添加输入数据的异步方法
const addInput = async () => {
  console.log(input.value);
  axios({
    method: "patch",
    url: conf.url + "/material/all",
    data: input.value,
  })
    .then((res) => {
      if (res.data.code === 0) {
        console.log(res.data.message);
        successMessage();
      } else {
        ErrorMessage();
      }
    })
    .catch((err) => {
      console.log(err);
      ErrorMessage();
    });
};

// 处理输入确认的函数
const handleInputConfirm = (item: input) => {
  // 检查输入值是否存在
  if (item.inputValue) {
    // 检查材料名称是否已定义
    if (item.materialName != undefined) {
      item.materialName.push(item.inputValue);
    } else {
      item.materialName = [item.inputValue];
    }
    // 清空输入框
    item.inputValue = "";
  }
};

// 组件挂载时执行的钩子函数
onMounted(() => {
  getInput();
});

const getInput = async () => {
  axios({
    method: "get",
    url: conf.url + "/material",
  })
    .then((res) => {
      input.value = res.data.data;
    })
    .catch((err) => {
      ElMessage({
        type: "error",
        message: "获取数据失败",
      });
      console.log(err);
    });
};
// 标签关闭事件的处理函数
const handleClose = (qualificationName: string, tag: string) => {
  console.log("删除标签", tag);
  // 遍历输入的值，根据资格名称移除对应的材料名称
  input.value.forEach((item) => {
    if (item.qualificationName === qualificationName) {
      item.materialName.splice(item.materialName.indexOf(tag), 1);
    }
  });
};
// 新增模块的渲染函数
const addModule = async () => {
  let error = false;
  // 此方法用于弹出输入框并添加资格名称
  ElMessageBox.prompt("请输入资格名称", "添加", {
    confirmButtonText: "确认添加",
    cancelButtonText: "取消添加",
    inputErrorMessage: "添加失败",
  })
    .then(({ value }) => {
      // 发送 POST 请求以添加新的资格名称
      axios({
        method: "post",
        url: conf.url + "/material",
        params: {
          qualificationName: value,
        },
      })
        .then((res) => {
          console.log(res.data);
          getInput(); // 刷新输入
        })
        .catch((err) => {
          ElMessage({
            type: "error",
            message: "添加失败",
          });
          error = true;
          console.log(err);
        });
      if (error) {
        ElMessage({
          type: "success",
          message: `成功添加${value}模块`,
        });
      }
    })
    .catch((err) => {
      console.log(err);

      // 处理取消操作
      if (err === "cancel") {
        ElMessage({
          type: "info",
          message: "取消添加",
        });
      }
    });
};
const deleteModule = async (id: number) => {
  ElMessageBox.confirm("确认删除该模块吗？", "提示", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消删除",
  })
    .then(() => {
      // 发送 DELETE 请求以删除资格名称
      axios({
        method: "delete",
        url: conf.url + "/material",
        params: {
          id: id,
        },
      })
        .then((res) => {
          console.log(res.data);
          getInput(); // 刷新输入
        })
        .catch((err) => {
          ElMessage({
            type: "error",
            message: "删除失败",
          });
          console.log(err);
        });
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch((err) => {
      console.log(err);
      // 处理取消操作
      if (err === "cancel") {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      }
    });
};
const editTitle = (id: number) => {
  ElMessageBox.prompt("请输入新的名称", "修改", {
    confirmButtonText: "确认修改",
    cancelButtonText: "取消修改",
    inputErrorMessage: "修改失败",
    inputValue: input.value.find((item) => item.id === id)?.qualificationName,
  })
    .then(({ value }) => {
      // 发送 PATCH 请求以修改资格名称
      console.log(value,id);
      
      axios({
        method: "patch",
        url: conf.url + "/material",
        data: {
          id: id,
          qualificationName: value,
        },
      })
        .then((res) => {
          console.log(res.data);
          getInput(); // 刷新输入
        })
        .catch((err) => {
          ElMessage({
            type: "error",
            message: "修改失败",
          });
          console.log(err);
        });
      ElMessage({
        type: "success",
        message: `成功修改${value}模块`,
      });
    })
    .catch((err) => {
      console.log(err);
      // 处理取消操作
      if (err === "cancel") {
        ElMessage({
          type: "info",
          message: "取消修改",
        });
      }
    });
};
</script>
<template>
  <el-scrollbar>
    <div class="container">
      <!-- 提交按钮，触发添加输入的函数 -->
      <el-affix :offset="50" style="margin-left: 7px">
        <el-button type="primary" @click="addInput">修改</el-button>
        <el-button type="primary" @click="addModule">新增模块</el-button>
      </el-affix>
      <!-- 输入模块的循环渲染，展示每个申请材料 -->
      <div class="module" v-for="(item, index) in input" :key="index">
        <!-- 资格名称的展示 -->
        <span class="title">
          {{ item.qualificationName
          }}<El-icon
            class="edit-icon"
            @click="editTitle(item.id)"
            color="gray"
            ><Edit
          /></El-icon>
          <El-icon
            @click="deleteModule(item.id)"
            style="float: right"
            color="gray"
            class="delete-icon"
            ><CircleClose
          /></El-icon>
        </span>
        <br /><br />
        <!-- 材料名称输入标签 -->
        <div class="tags">
          <el-scrollbar height="13rem">
            <el-tag type="info" size="small" style="margin-left: 5px"
              >材料:</el-tag
            >
            <!-- 渲染每个物料名称的标签 -->
            <el-tag
              v-for="tag in item.materialName"
              :key="tag"
              closable
              :disable-transitions="false"
              style="margin-left: 5px"
              size="small"
              @close="handleClose(item.qualificationName, tag)"
            >
              {{ tag }}
            </el-tag>
          </el-scrollbar>
        </div>
        <!-- 输入框组件，用于接收用户输入 -->
        <el-input
          ref="InputRef"
          v-model="item.inputValue"
          class="input-box"
          size="small"
          @keyup.enter="handleInputConfirm(item)"
          @blur="handleInputConfirm(item)"
          placeholder="请输入材料名称,按回车确认"
        />
      </div>
      <el-skeleton-item variant="text" style="margin-right: 16px" />
      <el-skeleton-item variant="text" style="width: 30%" />
    </div>
  </el-scrollbar>
</template>

<style scoped>
.delete-icon {
  opacity: 0.5;
  transition: all 0.2s ease-in-out;
}
.delete-icon:hover {
  opacity: 1;
  transform: scale(1.2);
}
.container {
  padding: 20px;
  padding-top: 25px;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
  overflow: scroll;
  user-select: none;
}
.module {
  width: 19rem;
  height: 20rem;
  border: 1px solid #ccc;
  margin: 6px;
  margin-top: 25px;
  padding: 11px;
  display: flex;
  display: inline-block;
  transition: all 0.3s ease-in-out;
  background-color: white;
}
.title {
  font-weight: bold;
}
.module:hover {
  box-shadow: 0 0 10px #ccc;
  transition: all 0.3s ease-in-out;
  transform: scale(1.055);
  cursor: pointer;
}
.tags {
  display: flex;
  flex-wrap: wrap;
  height: 14rem;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  margin-bottom: 10px;
  scrollbar-width: thin;
  overflow-y: auto;
}
.edit-icon {
  opacity: 0.5;
  transition: all 0.2s ease-in-out;
  margin-left: 5px;
}
.edit-icon:hover {
  opacity: 1;
  transform: scale(1.2);
}
</style>
